pepperstad.GUI = function (opts) {

    this.game = opts.game;
    this.resourceLoader = opts.resourceLoader;
    this.buttons = [];
    this.nextSpace = 0;

    var self = this,
        config = pepperstad.config,
        lang = this.resourceLoader.get("lang"),
        buildingInfoDialog;

    this.createButton = function (opts) {
        var button = new pepperstad.Button(opts);
        var space = this.nextSpace;
        button.createElement(50 * this.buttons.length + space);
        this.buttons.push(button);
    };

    this.createLabel = function (opts) {
        this.createSpacer();
        _.extend(opts, {
            smallText: true,
            id: "label" + (new Date()).getTime(),
            label: true
        });
        var button = new pepperstad.Button(opts);
        var space = this.nextSpace;
        button.createElement(50 * this.buttons.length + space);
        this.buttons.push(button);
    };

    this.createSpacer = function () {
        this.nextSpace += 30;
    };

    this.setAllButtonsActive = function (bActive) {
        var button, i;
        for (i = 0; i < this.buttons.length; i++) {
            button = this.buttons[i];
            button.setActive(bActive);
        }
    };

    this.setButtonActive = function (buttonId, bActive) {
        var button = _.find(this.buttons, function (b) {
            return b.id === buttonId;
        });
        button.setActive(bActive);
    };

    this.showStoryDialog = function (story) {
        $("#dialog").html(story.text).dialog({
            title: story.title,
            modal: true,
            position: [400, 200],
            width: 500,
            buttons: {
                "OK": function () {
                    $(this).dialog("close");
                    self.game.startGame();
                }
            }
        });
    };

    this.showUnitManager = function () {
        $("#dialog").html("Loading dialog...").load("dialogs/unit-manager.html #content",
            function () {
                $("#people-manager").find("tbody").append(rows);
                $("#loadmsg").remove();
                $("#people-manager").tablesorter();
            }).dialog({
                title: lang["Mayor"] + " : " + lang["AdministrateCitizens"],
                modal: true,
                position: [200, 100],
                width: 800,
                height: 600,
                buttons: {
                    "OK": function () {
                        $(this).dialog("close");
                    }
                }
            }).keyup(function (evt) {
                evt.stopPropagation();
            });
        $("#dialog").height(600); // bug workaround
        var rows = "";

        function personToRow(oPerson) {
            return "<tr><td>" + oPerson.name + "</td><td>" + oPerson.age + "</td>" +
                "<td>" + oPerson.strength + "</td><td> " + oPerson.happiness + "</td>" +
                "<td>" + oPerson.getJobName() + "</td><td>" + oPerson.listSkills() + " </td></tr>";
        }

        $.each(this.game.player.people, function (index, oPerson) {
            rows += personToRow(oPerson);
        });

    };

    this.closeBuildingInfo = function() {
        if ($("#dialog").hasClass("ui-dialog-content")) {
            $("#dialog").dialog("close");
            buildingInfoDialog = null;
        }
    };

    this.showBuildingInfo = function (struct) {
        if (!buildingInfoDialog) {
            buildingInfoDialog = $("#dialog").html("Loading dialog...").load("dialogs/structure-info.html #content", function () {
                updateFields();
            }).dialog({
                    title: "Structure info",
                    modal: false,
                    position: [config.playgroundWidth + config.layerOffsetX * 2,
                            config.layerOffsetY + config.playgroundHeight - 500],
                    width: 400,
                    buttons: {
                        "Close": function () {
                            self.closeBuildingInfo();
                        }
                    }
                }).keyup(function (evt) {
                    evt.stopPropagation();
                });
            $("#dialog").height(350); // bug workaround
        }
        updateFields();
        function updateFields() {
            $("#struct-type").text(struct.type.toUpperCase());
            $("#struct-state").text(struct.state).css("color", config.stateColors[struct.state]);
            $("#struct-name").text(struct.name);
            $("#struct-cap").text("Capacity: " + struct.getCapacity());
            $("#structure-info-jobs").find("tbody").empty();
            var rows = getJobRows();
            if (rows) {
                $("#structure-info-jobs").find("tbody").append(rows);
                $("#structure-info-jobs").show();
            }
            else {
                $("#structure-info-jobs").hide();
            }
            $("#structure-info-jobs").tablesorter();
        }
        function getJobRows() {
            var rows = "";
            _.each(struct.getJobs(), function (job) {
                if (job.employee)
                rows += "<tr><td>" + job.type + "</td><td>" + job.employee.name + "</td></tr>\n";
            });
            return rows;
        }
    };

    this.showStructureEditor = function (struct, fnCallBack) {
        $("#dialog").html("Loading dialog...").load("dialogs/structure-editor.html #content",
            function () {
                // set content and register event handler
                $("#struct-type").append(getRowsFromJSON("type", "type",
                    self.resourceLoader.get("buildings")));
                $("#struct-state").append(getRowsFromJSON("name", "name",
                    self.resourceLoader.get("structureState")));
                if (struct) {
                    $("#struct-type").val(struct.type);
                    $("#struct-state").val(struct.state);
                    $("#struct-name").val(struct.name);
                } else {
                    $("#struct-name").val();
                }
            }).dialog({
                title: "Structure editor",
                modal: true,
                position: [200, 100],
                width: 550,
                height: 100,
                buttons: {
                    "Save": function () {
                        fnCallBack(
                            $("#struct-type").val(),
                            $("#struct-name").val(),
                            $("#struct-state").val());
                        $(this).dialog("close");
                    }
                }
            }).keyup(function (evt) {
                evt.stopPropagation();
            });

        function getRowsFromJSON(sKey, sValue, aoJsonResource) {
            var retval = "";
            for (var i = 0; i < aoJsonResource.length; i++) {
                retval += "<option value=\"" + aoJsonResource[i][sKey] + "\">" + aoJsonResource[i][sValue] + "</option>\n";
            }
            return retval;
        }

        $("#dialog").height(100); // bug workaround
    };

};

pepperstad.Button = function (opts) {
    opts = opts || {};
    _.defaults(opts, {
        enabled: true
    });
    _.extend(this, opts);

    var self = this;

    this.setActive = function (bActive) {
        this.enabled = bActive;
        this.getElement().toggleClass("inactive", !bActive);
    };
    this.createElement = function (vertPosition) {
        $("body").append("<div class=\"button\" id=\"" + this.id + "\">" + setupTextMnemonic() + "</div>");
        self.getElement().css("top", vertPosition).bind("click", function () {
            if (self.enabled && !self.label) {
                self.clickHandler();
            }
        });
        if (self.keyCode) {
            self.addKeyHandler();
        }
        if (!self.enabled) {
            self.addClass("inactive");
        }
        if (opts.smallText) {
            self.addClass("smallFont");
        }
        if (opts.label) {
            self.addClass("label");
        }
    };
    this.getElement = function () {
        return $("#" + this.id);
    };
    this.addClass = function (sClass) {
        this.getElement().addClass(sClass);
    };
    this.addKeyHandler = function () {
        $(document).keyup(function (evt) {
            if (evt.which == self.keyCode) {
                self.getElement().click();
            }
        });
    };

    function setupTextMnemonic() {
        var index = self.text.indexOf("["), first, ch, last;
        if (index > -1) {
            first = index > 0 ? self.text.substring(0, index) : "";
            ch = self.text.substr(index + 1, 1);
            last = self.text.substring(index + 3, self.text.length);
            return first + "<span style=\"text-decoration: underline;\">" + ch + "</span>" + last;
        }
        return self.text;
    }

};
